<?php

namespace app\admin\controller\doctor;

use app\common\controller\Backend;
use think\Db;
use fast\Tree;

/**
 * 医护管理-专家列表
 *
 * @icon fa fa-circle-o
 */
class Doctor extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Medic;
        $this->models = new \app\admin\model\Project;

        $data = Db::table('fa_categorys')
            ->where('type',1)
            ->select();

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $arr = Db::table('fa_project')
                    ->where('category_id', $v['id'])
                    ->select();
                if (empty($arr)){
                    unset($data[$k]);
                }else{
                    $data[$k]['arr'] = $arr;
                }

            }
        }


        $this->view->assign("parentList", $data);
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('type','专家')
                //->where('admin_id', 'in', [0])
                ->order(['sort'=>'desc','id'=>'desc'])
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $pan = Db::table('fa_medic')
                    ->where('username',$params['username'])
                    ->find();

                if (!empty($pan)){
                    $this->error(__('专家或护士已存在该账号'));
                }

                if (empty($params['speciality'][0])){
                    $this->error(__('必须选择一个擅长'));
                }

                foreach ($params['speciality'] as $k=>$v){
                    $str = Db::table('fa_project')
                        ->where('id',$v)
                        ->find();
                    $strs[] = $str['project_name'];
                }

                $params['project_id'] = implode(',',$params['speciality']);
                $params['speciality'] = implode(',',$strs);
                $params['type'] = '专家';

                //var_dump($params);die();

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $row->specialitys = explode(',',$row->speciality);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $pan = Db::table('fa_medic')
                ->where('username',$params['username'])
                ->find();

            if ($row->id != $pan['id']){
                if (!empty($pan)){
                    $this->error(__('专家或护士已存在该账号'));
                }

            }

            if (empty($params['speciality'][0])){
                $this->error(__('必须选择一个擅长'));
            }
            foreach ($params['speciality'] as $k=>$v){
                $str = Db::table('fa_project')
                    ->where('id',$v)
                    ->find();
                $strs[] = $str['project_name'];
            }

            $params['project_id'] = implode(',',$params['speciality']);
            $params['speciality'] = implode(',',$strs);

            //var_dump($params);die();
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
